package com.jy.api.service.impl;

import com.jy.api.dao.CallTranDao;
import com.jy.api.dao.StoreDao;
import com.jy.api.dao.StoreOrderDao;
import com.jy.api.dao.WechatSendTemplateDao;
import com.jy.api.domain.*;
import com.jy.api.pay.result.PayResult;
import com.jy.api.service.MemberV1Service;
import com.jy.api.service.StoreOrderService;
import com.jy.api.util.MyDateUtils;
import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import sun.rmi.runtime.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by lihu on 2018/1/17.
 */
@Service
@Slf4j
public class StoreOrderServiceImpl implements StoreOrderService {

    @Autowired
    StoreOrderDao storeOrderDao;

    @Autowired
    MemberV1Service memberV1Service;

    @Autowired
    WechatSendTemplateDao wechatSendTemplateDao;

    @Autowired
    private CallTranDao callTranDao;
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private XStream xstream;

    @Override
    @Transactional
    public void handleStoreOrder(PayResult payResult) {
        StoreOrder storeOrder = storeOrderDao.findOne(payResult.getOutTradeNo());
        storeOrder.setSuccess(true);
        WechatSendTemplate wechatSendTemplate = wechatSendTemplateDao.findOne(storeOrder.getSendId());
        memberV1Service.sendActivityWechat(storeOrder.getStoreId(), wechatSendTemplate);
    }

    @Override
    @Transactional
    public void handleCallOrder(String xml) {
        SwiftPassPaymentNotify notify = (SwiftPassPaymentNotify) xstream.fromXML(xml, new SwiftPassPaymentNotify());
        CallTran callTran = callTranDao.findOne(notify.getOutTradeNo());
        if (notify.isPaymentSuccess()) {
            callTran.setPayTime(MyDateUtils.getDateFormatDd(notify.getTimeEnd(), "yyyy-MM-dd HH:mm:ss"));
            callTran.setChannel(notify.getTradeType());
            callTran.setStatus(OrderStatus.FINISHED);
            callTranDao.save(callTran);
        } else {
            if (callTran.getStatus().equals(OrderStatus.INIT)) {
                // 已经成功处理过该消息
                return;
            } else {
                callTran.setStatus(OrderStatus.INIT);
                callTranDao.save(callTran);
            }
        }
    }
}